#coding: utf-8
from django.db import models
from django.urls import reverse
from unidecode import unidecode
from django.template.defaultfilters import slugify
from AppLogin.models import Users
from datetime import datetime
from django.utils import timezone
from ckeditor_uploader.fields import RichTextUploadingField

# Create your models here.
'''
文章模型
根据文章标题手动生成slug, 并把slug放到url里。slug最大的作用就是便于读者和搜索引擎直接从url中了解文章大概包含了什么内容，
我们还要考虑到slug可能会随文章title的变化而改变导致后续网站上出现很多坏连接，所以我们希望slug只是在首次创建文章时生成，
而不会随后续title的变化而改变。除此以外，我们还要解决中文标题无法生成slug的问题。最好的解决方案就是重写模型models的save方法
当id或slug为空时，利用unidecode对中文解码，利用slugify方法根据标题手动生成slug。
'''
class Article(models.Model):
    STATUS_CHOICES = (('d', '草稿'),('p', '发表'), )
    title = models.CharField('标题',max_length=200,unique=True)
    slug = models.SlugField('slug', max_length=60, blank=True)
    body = RichTextUploadingField('正文')
    pub_date = models.DateTimeField('发布时间', null=True)
    create_date = models.DateTimeField('创建时间', auto_now_add=True)
    mod_date = models.DateTimeField('修改时间', auto_now=True)
    status = models.CharField('文章状态', max_length=1, choices=STATUS_CHOICES, default='d')
    views = models.PositiveIntegerField('浏览量', default=0)
    author = models.ForeignKey(Users, verbose_name='作者', on_delete=models.CASCADE)
    category = models.ForeignKey('Category', verbose_name='分类', on_delete=models.CASCADE, blank=False, null=False)
    tags = models.ManyToManyField('Tag', verbose_name='标签集合', blank=True)
    users_like = models.ManyToManyField(Users,related_name='articles_liked',blank=True)

    def __str__(self):
        return self.title

    def save(self,*args,**kwargs):
        if not self.id or not self.slug:
            self.slug = slugify(unidecode(self.title))
        super().save(*args,**kwargs)

    def get_absolute_url(self):
        return reverse('blog:article_detail',args=[str(self.id),self.slug])

    def clean(self):
        if self.status == 'd' and self.pub_date is not None:
            self.pub_date = None
        if self.status == 'p' and self.pub_date is None:
            self.pub_date = datetime.now()

    def viewed(self):
        self.views += 1
        self.save(update_fields=['views'])

    def published(self):
        self.status = 'p'
        self.pub_date = datetime.now()
        self.save(update_fields=['status','pub_date'])

    class Meta:
        ordering = ['-pub_date']
        verbose_name = "文章"
        verbose_name_plural = verbose_name

#文章类别模型
class Category(models.Model):
    name = models.CharField('文章类别',max_length=30,unique=True)
    slug = models.SlugField('slug', max_length=40)
    #指向自己，进行判断有没有子类
    parent_category = models.ForeignKey('self',verbose_name='父级分类',blank=True,null=True,on_delete=models.CASCADE)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('blog:category_detail',args=[self.slug])

    def has_child(self):
        if self.category_set.all().count() > 0: #通过一查询多采用这种方式：一.多_set如：Users.author_set.all()
            return True

    def save(self,*args,**kwargs):
        if not self.id or not self.slug:
            self.slug = slugify(unidecode(self.name))
        super().save(*args,**kwargs)


    class Meta:
        ordering = ['name']
        verbose_name = "文章分类"
        verbose_name_plural = verbose_name

#文章标签模型
class Tag(models.Model):
    name = models.CharField('标签名',max_length=30,unique=True)
    slug = models.SlugField('slug', max_length=40)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('blog:tag_detail',args=[self.slug])

    def get_article_count(self):
        return Article.objects.filter(tags__slug=self.slug).count()

    def save(self,*args,**kwargs):
        if not self.id or not self.slug:
            self.slug = slugify(unidecode(self.name))
        super().save(*args,**kwargs)

    class Meta:
        ordering = ['name']
        verbose_name = "文章标签"
        verbose_name_plural = verbose_name

class Link(models.Model):
    name = models.CharField(max_length=40, verbose_name='链接名')
    url = models.URLField(max_length=40, verbose_name='链接地址')
    create_time = models.DateTimeField(auto_now_add=True, verbose_name=u'创建时间')

    class Meta:
        verbose_name = '友情链接'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

class Comment(models.Model):
    user = models.ForeignKey(Users,on_delete=models.CASCADE,verbose_name='用户')
    article = models.ForeignKey(Article,on_delete=models.CASCADE,verbose_name='文章')
    text = models.TextField(verbose_name='评论')
    is_removed = models.BooleanField(default=False)
    parent = models.ForeignKey('self',on_delete=models.CASCADE,default=None,blank=True,null=True,verbose_name='父评论')
    #likes_count = models.PositiveIntegerField(default=0,verbose_name='点赞数')
    create_time = models.DateTimeField(verbose_name='创建时间', default=datetime.now)
    update_time = models.DateTimeField(verbose_name='修改时间', blank=True, null=True)

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = verbose_name
        ordering = ['-create_time']

    def __str__(self):
        return self.article.title